from .common import *
def setadminpwd():
    "设置初始化用户 登录码和密码"
    username=times()
    password="111111"
    try:
        sqlite("admin",model_app_path).where("id",1).update({'username':username,'password':md5("kcw"+password)})
    except:
        return errorjson(msg="设置失败")
    else:
        return successjson({"username":username,"password":password})
def index():
    if sysisphone():
        return response.tpl("../tplm/admin/index")
    else:
        return response.tpl()
def admin():
    if sysisphone():
        return response.tpl("../tplm/admin/admin")
    else:
        return response.tpl()
def role():
    if sysisphone():
        return response.tpl("../tplm/admin/role")
    else:
        return response.tpl()
def adminlog():
    if sysisphone():
        return response.tpl("../tplm/admin/adminlog")
    else:
        return response.tpl()
def logdeta(id):
    "日志明细"
    data=sqlite("admin_log t1",model_app_path).field("t1.*,t2.icon,t2.name,t2.phone").join("admin t2","t1.user_id=t2.id","LEFT").where("t1.id",id).find()
    data['routeparamarr']=json_decode(data['routeparam'])
    data['dataparamarr']=json_decode(data['dataparam'])
    return successjson(data)
def loglist():
    "日志列表"
    where="1=1"
    kw=request.args.get('kw')
    types=request.args.get('types')
    method=request.args.get('method')
    pagenow=request.args.get('pagenow')
    pagesize=request.args.get('pagesize')
    if kw:
        where+=" and t2."+types+" like '%"+kw+"%'"
    if method:
        where+=" and method='"+method+"'"
    if not pagenow:
        pagenow=1
    else:
        pagenow=int(pagenow)
    if not pagesize:
        pagesize=10
    else:
        pagesize=int(pagesize)
    lists=sqlite("admin_log t1",model_app_path).order("t1.id desc").field("t1.*,t2.icon,t2.name,t2.phone").join("admin t2","t1.user_id=t2.id","LEFT").where(where).page(pagenow,pagesize).select()
    count=sqlite("admin_log t1",model_app_path).join("admin t2","t1.user_id=t2.id","LEFT").where(where).count()
    data=return_list(lists,count,pagenow,pagesize)
    return successjson(data)
def deletelog(id=0):
    "删除日志"
    G.setadminlog="删除日志"
    if id:
        sqlite("admin_log",model_app_path).where('id',id).delete()
        return successjson()
    else:
        try:
            id=request.get_json()
            sqlite("admin_log",model_app_path).where('id','in',id).delete()
        except:
            return errorjson(msg="失败")
        else:
            return successjson()
def getpluglist(modular="intapp"):
    "本地插件列表"
    path="app/"+modular+"/controller/"
    lis=os.listdir(path)
    lists=[]
    for k in lis:
        if not os.path.isfile(path+k) and '__' not in k:
            lists.append(k)
    data=sqlite('plug',model_app_path).select()
    # print(data)
    i=0
    for k in data:
        # k['value']=k['modular']+"/"+k['name']
        data[i]['role']=json_decode(k['role'])
        # if k['name'] not in lists:
        #     # print(k['name'],lists)
        #     del data[i]
        i+=1
    return successjson(data)
def dellogin():
    G.setadminlog="退出所有会话"
    shutil.rmtree(config.session['path'])
    return successjson()
def getlist(id=0):
    "获取列表"
    if id:
        return successjson(sqlite("admin",model_app_path).field('id,icon,username,phone,nickname,name,logintime,addtime').find(id))
    where=None
    kw=request.args.get('kw')
    pagenow=request.args.get('pagenow')
    pagesize=request.args.get('pagesize')
    if kw:
        where=[("username","like","%"+str(kw)+"%"),'or',("name","like","%"+str(kw)+"%"),'or',("nickname","like","%"+str(kw)+"%"),'or',("phone","like","%"+str(kw)+"%")]
    if not pagenow:
        pagenow=1
    else:
        pagenow=int(pagenow)
    if not pagesize:
        pagesize=10
    else:
        pagesize=int(pagesize)
    lists=sqlite("admin",model_app_path).field("t1.*,t2.title,t2.describes").alias('t1').join("role t2","t1.role=t2.id","LEFT").where(where).page(pagenow,pagesize).select()
    count=sqlite("admin",model_app_path).where(where).count()
    data=return_list(lists,count,pagenow,pagesize)
    return successjson(data)
def insert():
    G.setadminlog="添加管理员"
    try:
        data=request.get_json()
        if not data['username'] or not data['password']:
            return errorjson(msg="请输入用户名或密码")
        data.update(logintime=times(),addtime=times())
        sqlite("admin",model_app_path).insert(data)
    except:
        return errorjson(msg="失败")
    else:
        return successjson()
def delete(id=0):
    "批量删除"
    G.setadminlog="删除管理员"
    if id:
        sqlite("admin",model_app_path).where('id',id).delete()
        return successjson()
    else:
        try:
            id=request.get_json()
            if 1 in id:
                id.remove(1)
            sqlite("admin",model_app_path).where('id','in',id).delete()
        except:
            return errorjson(msg="失败")
        else:
            return successjson()
def update(id=0):
    "更新内容"
    G.setadminlog="修改管理员"
    data=request.get_json()
    if not id:
        id=data['id']
    try:
        data.pop('logintime')
        data.pop('addtime')
        data.pop('password')
        del data['title']
        del data['describes']
    except:pass
    else:
        sqlite("admin",model_app_path).where("id",id).update(data)
    return successjson()
def setpwd():
    "设置管理员登录密码"
    G.setadminlog="设置管理员登录密码"
    data=request.get_json()
    try:
        sqlite("admin",model_app_path).where("id",data['id']).update({'password':data['password']})
    except:
        return errorjson(msg="设置失败")
    else:
        return successjson()
def setmypwd():
    """设置自己的登录密码"""
    G.setadminlog="设置自己的登录密码"
    data=request.get_json()
    try:
        sqlite("admin",model_app_path).where("id",G.userinfo['id']).update({'password':data['password']})
    except:
        return errorjson(msg="设置失败")
    else:
        return successjson()
def getrolelist(id=0):
    "获取角色"
    if id:
        return successjson(sqlite("role",model_app_path).find(id))
    where=None
    kw=request.args.get('kw')
    pagenow=request.args.get('pagenow')
    pagesize=request.args.get('pagesize')
    if kw:
        where=[("title","like","%"+str(kw)+"%")]
    if not pagenow:
        pagenow=1
    else:
        pagenow=int(pagenow)
    if not pagesize:
        pagesize=10
    else:
        pagesize=int(pagesize)
    lists=sqlite("role",model_app_path).where(where).page(pagenow,pagesize).select()
    for k in lists:
        k['roleroute']=json_decode(k['roleroute'])
    count=sqlite("role",model_app_path).where(where).count()
    data=return_list(lists,count,pagenow,pagesize)
    return successjson(data)
def insertrole():
    G.setadminlog="添加角色"
    try:
        data=request.get_json()
        data.update(updtime=times(),addtime=times())
        data['roleroute']=json_encode(data['roleroute'])
        sqlite("role",model_app_path).insert(data)
    except:
        return errorjson(msg="失败")
    else:
        return successjson()
def updaterole(id=0):
    "更新内容"
    G.setadminlog="修改角色权限"
    data=request.get_json()
    if not id:
        id=data['id']
    id=int(id)
    if id==1:
        return errorjson(msg="该角色不允许修改")
    try:
        data.pop('updtime')
        data.pop('addtime')
        data['roleroute']=json_encode(data['roleroute'])
    except:pass
    else:
        sqlite("role",model_app_path).where("id",id).update(data)
    return successjson()
def deleterole():
    "批量删除"
    G.setadminlog="删除角色"
    try:
        id=request.get_json()
        try:
            id.remove(1)
        except:pass
        sqlite("role",model_app_path).where('id','in',id).delete()
    except:
        return errorjson(msg="失败")
    else:
        return successjson()